import 'dart:convert';
import 'dart:ui';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:gzx_dropdown_menu/gzx_dropdown_menu.dart';
import '../../http/Api.dart';
import '../../http/HttpUtil.dart';
import '../../util/SignUtil.dart';
import '../../base/Constant.dart';
import '../../entity/goods_list_entity.dart';
import '../goods/GoodsDetail.dart';
import 'package:cached_network_image/cached_network_image.dart';

class SearchGoodsListPage extends StatefulWidget {
  String search;
  SearchGoodsListPage({Key key, @required this.search}) : super(key: key);

  _SearchGoodsListPageState createState() => _SearchGoodsListPageState();
}

class _SearchGoodsListPageState extends State<SearchGoodsListPage> {
  List<GoodsModelData> homeListData = new List();
  String search = '';
  GZXDropdownMenuController _dropdownMenuController =
      GZXDropdownMenuController();
  List<String> sortList = ["价格", "销量", '佣金'];
  var _scaffoldKey = new GlobalKey<ScaffoldState>();
  GlobalKey _stackKey = GlobalKey();
  EasyRefreshController _controller = new EasyRefreshController();
  final _searchController = TextEditingController();
  int page = 1;
  int currentShow = 1; //0 正常 1 网格
  String sort = 'total_sales_des';
  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);

    return Container(
      child: new Scaffold(
          appBar: PreferredSize(
            child: AppBar(
              brightness: Brightness.light,
              backgroundColor: white,
              elevation: 0,
            ),
            preferredSize: Size(0, 0),
          ),
          body: new Stack(
            key: _stackKey,
            children: <Widget>[
              new Column(
                children: <Widget>[
                  Container(
                    height: kToolbarHeight,
                    color: white,
                    alignment: Alignment.center,
                    child: new Row(
                      children: <Widget>[
                        Padding(
                          padding: EdgeInsets.all(0),
                          child: IconButton(
                            onPressed: () {
                              Navigator.of(context).pop();
                            },
                            icon: Icon(
                              Icons.arrow_back_ios,
                              color: black_99,
                            ),
                          ),
                        ),
                        Expanded(
                          flex: 1,
                          child: Container(
                            margin: EdgeInsets.fromLTRB(
                                ScreenUtil.getInstance().setHeight(DP_10),
                                0,
                                ScreenUtil.getInstance().setHeight(DP_10),
                                0),
                            height: ScreenUtil.getInstance().setHeight(DP_60),
                            decoration: BoxDecoration(
                                color: Color.fromARGB(255, 245, 245, 245),
                                borderRadius: BorderRadius.circular(20.0)),
                            child: ConstrainedBox(
                              constraints: BoxConstraints(maxHeight: DP_80),
                              child: TextField(
                                style: TextStyle(
                                    fontSize:
                                        ScreenUtil.getInstance().setSp(32)),
                                controller: _searchController,
                                keyboardAppearance: Brightness.light,
                                maxLines: 1,
                                cursorColor: mainColor,
                                decoration: new InputDecoration(
                                    // contentPadding: EdgeInsets.all(0),
                                    prefixIcon: Icon(
                                      Icons.search,
                                      color: Colors.black45,
                                    ),
                                    hintText: "搜索商品、品牌",
                                    suffixIcon: ClipOval(
                                      child: Container(
                                        child: Icon(
                                          Icons.clear,
                                          color: Colors.white,
                                          size: ScreenUtil.getInstance()
                                              .setHeight(DP_30),
                                        ),
                                        margin: EdgeInsets.fromLTRB(
                                            80,
                                            ScreenUtil.getInstance()
                                                .setHeight(DP_15),
                                            ScreenUtil.getInstance()
                                                .setHeight(DP_15),
                                            ScreenUtil.getInstance()
                                                .setHeight(DP_15)),
                                        decoration: BoxDecoration(
                                            color: Colors.black45,
                                            borderRadius: BorderRadius.circular(
                                                ScreenUtil.getInstance()
                                                    .setHeight(DP_90))),
                                      ),
                                    ),
                                    border: InputBorder.none,
                                    hintStyle: TextStyle(
                                        color: Colors.black45,
                                        fontSize: ScreenUtil.getInstance()
                                            .setSp(NORMAL_FONT_SIZE))),
                              ),
                            ),
                          ),
                        ),
                        GestureDetector(
                          child: Container(
                              alignment: Alignment.center,
                              width: ScreenUtil.getInstance().setWidth(DP_120),
                              child: Text('确定',
                                  style: TextStyle(
                                      color: black_99,
                                      fontSize: ScreenUtil.getInstance()
                                          .setSp(NORMAL_FONT_SIZE)))),
                          onTap: () {
                            search = _searchController.text;
                            loadList();
                          },
                        )
                      ],
                    ),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Expanded(
                        flex: 2,
                        child: Container(
                          color: white,
                          padding: EdgeInsets.fromLTRB(0,
                              ScreenUtil.getInstance().setHeight(DP_8), 0, 0),
                          height: ScreenUtil.getInstance().setHeight(DP_60),
                          child: GZXDropDownHeader(
                            items: [
                              GZXDropDownHeaderItem(sortList[0]),
                              GZXDropDownHeaderItem(sortList[1]),
                              GZXDropDownHeaderItem(sortList[2]),
                            ],
                            stackKey: _stackKey,
                            controller: _dropdownMenuController,
                            onItemTap: (index) {},
                            height: ScreenUtil.getInstance().setHeight(DP_60),
                            color: white,
                            borderWidth: 1,
                            borderColor: white,
                            dividerColor: white,
                            style: TextStyle(
                                color: black_99,
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(SMALL_FONT_SIZE)),
                            dropDownStyle: TextStyle(
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE),
                              color: mainColor,
                            ),
                            iconSize: ScreenUtil.getInstance().setHeight(DP_40),
                            iconColor: black_99,
                            iconDropDownColor: mainColor,
                          ),
                        ),
                      ),
                      Container(
                        height: ScreenUtil.getInstance().setHeight(DP_60),
                        color: white,
                        child: IconButton(
                          onPressed: () {
                            setState(() {
                              currentShow =
                                  (currentShow == 0 ? currentShow = 1 : 0);
                            });
                          },
                          icon: Image.asset(currentShow == 1
                              ? 'images/icon_list_vertical.png'
                              : 'images/icon_list_transverse.png'),
                        ),
                      ),
                    ],
                  ),
                  new Container(
                    height: MediaQuery.of(context).size.height -
                        kToolbarHeight -
                        ScreenUtil.getInstance().setHeight(DP_60) -
                        MediaQueryData.fromWindow(window).padding.top,
                    color: f0Color,
                    padding: EdgeInsets.all(ScreenUtil.getInstance().setHeight(10)),
                    child: new EasyRefresh(
                      controller: _controller,
                      header: MaterialHeader(),
                      footer: MaterialFooter(),
                      enableControlFinishLoad: true,
                      enableControlFinishRefresh: true,
                      child: currentShow == 0
                          ? ListView.separated(
                              itemBuilder: _renderRow,
                              separatorBuilder:
                                  (BuildContext context, int index) {
                                return Container(
                                  color: divideColor,
                                  height: 1,
                                );
                              },
                              itemCount: homeListData == null
                                  ? 0
                                  : homeListData.length)
                          : GridView.builder(
                              shrinkWrap: true,
                              gridDelegate:
                                  SliverGridDelegateWithFixedCrossAxisCount(
                                      crossAxisCount: 2,
                                      mainAxisSpacing: ScreenUtil.getInstance().setHeight(10),
                                      crossAxisSpacing: ScreenUtil.getInstance().setHeight(10),
                                      childAspectRatio: 0.62),
                              itemBuilder: (context, index) {
                                return getItemContainer(context, index);
                              },
                              itemCount: homeListData == null
                                  ? 0
                                  : homeListData.length,
                            ),
                      onRefresh: () async {
                        page = 1;
                        loadList();
                      },
                      onLoad: () async {
                        page++;
                        loadList();
                      },
                    ),
                  ),
                ],
              ),
              GZXDropDownMenu(
                controller: _dropdownMenuController,
                animationMilliseconds: 0,
                menus: [
                  GZXDropdownMenuBuilder(
                      dropDownHeight:
                          ScreenUtil.getInstance().setHeight(DP_80) * 2 + 2,
                      dropDownWidget: new Column(
                        children: <Widget>[
                          Divider(
                            height: 1,
                            color: grey,
                          ),
                          new GestureDetector(
                            onTap: () {
                              setState(() {
                                sortList = ["价格", "销量", '佣金'];
                                sortList[0] = "价格升序";
                                _dropdownMenuController.hide();
                                sort = 'price_asc';
                                loadList();
                              });
                            },
                            child: Container(
                              width: double.infinity,
                              height: ScreenUtil.getInstance().setHeight(DP_80),
                              padding: EdgeInsets.all(10),
                              child: Text('价格升序'),
                            ),
                          ),
                          Divider(
                            height: 1,
                            color: grey,
                          ),
                          new GestureDetector(
                            onTap: () {
                              setState(() {
                                sortList = ["价格", "销量", '佣金'];
                                sortList[0] = "价格降序";
                                _dropdownMenuController.hide();
                                sort = 'price_des';
                                loadList();
                              });
                            },
                            child: Container(
                              width: double.infinity,
                              height: ScreenUtil.getInstance().setHeight(DP_80),
                              padding: EdgeInsets.all(10),
                              child: Text('价格降序'),
                            ),
                          ),
                        ],
                      )),
                  GZXDropdownMenuBuilder(
                      dropDownHeight:
                          ScreenUtil.getInstance().setHeight(DP_80) * 2 + 2,
                      dropDownWidget: new Column(
                        children: <Widget>[
                          Divider(
                            height: 1,
                            color: grey,
                          ),
                          new GestureDetector(
                            onTap: () {
                              setState(() {
                                sortList = ["价格", "销量", '佣金'];
                                sortList[1] = "销量升序";
                                _dropdownMenuController.hide();
                                sort = 'total_sales_asc';
                                loadList();
                              });
                            },
                            child: Container(
                              width: double.infinity,
                              height: ScreenUtil.getInstance().setHeight(DP_80),
                              padding: EdgeInsets.all(10),
                              child: Text('销量升序'),
                            ),
                          ),
                          Divider(
                            height: 1,
                            color: grey,
                          ),
                          new GestureDetector(
                            onTap: () {
                              setState(() {
                                sortList = ["价格", "销量", '佣金'];
                                sortList[1] = "销量降序";
                                _dropdownMenuController.hide();
                                sort = 'total_sales_des';
                                loadList();
                              });
                            },
                            child: Container(
                              width: double.infinity,
                              height: ScreenUtil.getInstance().setHeight(DP_80),
                              padding: EdgeInsets.all(10),
                              child: Text('销量降序'),
                            ),
                          ),
                        ],
                      )),
                  GZXDropdownMenuBuilder(
                      dropDownHeight:
                          ScreenUtil.getInstance().setHeight(DP_80) * 2 + 2,
                      dropDownWidget: new Column(
                        children: <Widget>[
                          Divider(
                            height: 1,
                            color: grey,
                          ),
                          new GestureDetector(
                            onTap: () {
                              setState(() {
                                sortList = ["价格", "销量", '佣金'];
                                sortList[2] = "佣金升序";
                                _dropdownMenuController.hide();
                                sort = 'tk_total_commi_asc';
                                loadList();
                              });
                            },
                            child: Container(
                              width: double.infinity,
                              height: ScreenUtil.getInstance().setHeight(DP_80),
                              padding: EdgeInsets.all(10),
                              child: Text('佣金升序'),
                            ),
                          ),
                          Divider(
                            height: 1,
                            color: grey,
                          ),
                          new GestureDetector(
                            onTap: () {
                              setState(() {
                                sortList = ["价格", "销量", '佣金'];
                                sortList[2] = "佣金降序";
                                _dropdownMenuController.hide();
                                sort = 'tk_total_commi_des';
                                loadList();
                              });
                            },
                            child: Container(
                              width: double.infinity,
                              height: ScreenUtil.getInstance().setHeight(DP_80),
                              padding: EdgeInsets.all(10),
                              child: Text('佣金降序'),
                            ),
                          ),
                        ],
                      )),
                ],
              ),
            ],
          )),
    );
  }

  Widget _renderRow(BuildContext context, int index) {
    var price = RichText(
      textAlign: TextAlign.left,
      text: TextSpan(style: TextStyle(color: Colors.red), children: [
        TextSpan(text: '¥', style: TextStyle(fontSize: 12.0)),
        TextSpan(
            text: homeListData[index].price, style: TextStyle(fontSize: 18.0)),
        TextSpan(
          text: homeListData[index].old_price,
          style: TextStyle(
              fontSize: 12.0,
              color: Colors.grey,
              decoration: TextDecoration.lineThrough,
              decorationColor: Colors.grey),
        ),
      ]),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
    return new GestureDetector(
      onTap: () {
        //处理点击事件
        GoodsModelData model = homeListData[index];

        Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
          return GoodsDetailPage(
            goods_id: model.goods_id,
            img: model.img,
          );
        }));
      },
      child: Container(
        padding: EdgeInsets.all(10),
        color: white,
        child: new Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            homeListData[index].img == ""
                ? Image.asset('images/pic_default.png',
                    width: ScreenUtil.getInstance().setWidth(180),
                    fit: BoxFit.fill,
                    height: ScreenUtil.getInstance().setWidth(180))
                : CachedNetworkImage(
                    imageUrl:Api.BaseUrl +
                            'public/upload/' +
                            homeListData[index].img.replaceAll('\\', '/'),
                    width: ScreenUtil.getInstance().setHeight(180),
                    height: ScreenUtil.getInstance().setHeight(180),
                    fit: BoxFit.fill,
                  ),
            Expanded(
              flex: 1,
              child: Container(
                padding: EdgeInsets.fromLTRB(10, 5, 5, 5),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      homeListData[index].goods_name,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          fontSize: ScreenUtil.getInstance().setSp(30),
                          color: black,
                          fontWeight: FontWeight.bold),
                    ),
                    Row(
                      children: <Widget>[
                        Expanded(
                          flex: 1,
                          child: price,
                        ),
                        Container(
                          margin: EdgeInsets.all(kMargin5),
                          child: Text('已售' + homeListData[index].sales_volume,
                              style: TextStyle(
                                  fontSize: 12.0, color: Colors.grey)),
                        ),
                      ],
                    ),

                    // Container(
                    //   margin: EdgeInsets.all(kMargin5),
                    //   child: Row(
                    //     children: <Widget>[
                    //       Expanded(
                    //         flex: 1,
                    //         child: Row(
                    //           children: <Widget>[quanHeader, quan],
                    //         ),
                    //       ),
                    //       Expanded(flex: 2, child: yongjin)
                    //     ],
                    //   ),
                    // ),
                    // Padding(
                    //   padding: EdgeInsets.fromLTRB(0, 3, 5, 0),
                    //   child: Text(
                    //     homeListData[index].coupon_amount,
                    //     style: TextStyle(
                    //       fontSize: ScreenUtil.getInstance().setSp(26),
                    //       color: black_99,
                    //     ),
                    //   ),
                    // ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  //商品单个cell
  //商品单个cell
  getItemContainer(BuildContext context, int index) {
    return new GestureDetector(
        onTap: () {
          //处理点击事件
          GoodsModelData model = homeListData[index];
          Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
            return GoodsDetailPage(
              goods_id: model.goods_id,
              img: model.img,
            );
          }));
        },
        child: Container(
            padding: EdgeInsets.all(ScreenUtil.getInstance().setHeight(10)),
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(kMargin10)),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                homeListData[index].img == ''
                    ? Image.asset('images/pic_default.png')
                    : CachedNetworkImage(
                        width: (ScreenUtil.getInstance().setWidth(750) -
                                kMargin20) /
                            2,
                        height: (ScreenUtil.getInstance().setWidth(750) -
                                kMargin20) /
                            2,
                        fit: BoxFit.fill,
                        imageUrl: Api.BaseUrl +
                            'public/upload/' +
                            homeListData[index].img.replaceAll('\\', '/'),
                        placeholder: (context, url) => Image.asset(
                          'images/pic_default.png',
                          width: (ScreenUtil.getInstance().setWidth(750) -
                                  kMargin20) /
                              2,
                          height: (ScreenUtil.getInstance().setWidth(750) -
                                  kMargin20) /
                              2,
                        ),
                        errorWidget: (context, url, error) => Image.asset(
                          'images/pic_default.png',
                          width: (ScreenUtil.getInstance().setWidth(750) -
                                  kMargin20) /
                              2,
                          height: (ScreenUtil.getInstance().setWidth(750) -
                                  kMargin20) /
                              2,
                        ),
                      ),
                Container(
                  height: 2,
                ),
                Row(
                  children: <Widget>[
                    ClipOval(
                        child: Image.asset(
                      'images/logo.png',
                      width: ScreenUtil.getInstance().setWidth(38),
                      height: ScreenUtil.getInstance().setWidth(38),
                    )),
                    Container(
                        margin: EdgeInsets.only(
                            left: ScreenUtil.getInstance().setWidth(5)),
                        child: Text(
                          '日尚臻选',
                          style: TextStyle(
                              fontSize: ScreenUtil.getInstance().setSp(22),
                              color: Colors.grey),
                        ))
                  ],
                ),
                Container(
                  height: 2,
                ),
                Text(
                  homeListData[index].goods_name,
                  maxLines: 2,
                  style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: ScreenUtil.getInstance().setSp(30)),
                ),
                Container(
                  height: 4,
                ),
                Container(
                  margin: EdgeInsets.all(kMargin5),
                  child: RichText(
                    textAlign: TextAlign.left,
                    text: TextSpan(
                        style: TextStyle(color: Colors.red),
                        children: [
                          // TextSpan(text: '¥', style: TextStyle(fontSize: 12.0)),
                          TextSpan(
                              // text: shopData[index].zk_final_price,
                              text: MONEY + homeListData[index].price,
                              style: TextStyle(
                                  fontSize: ScreenUtil.getInstance().setSp(30),
                                  fontWeight: FontWeight.w600)),
                          TextSpan(
                            // text: shopData[index].reserve_price,
                            text: homeListData[index].old_price,
                            style: TextStyle(
                                fontSize: 12.0,
                                color: Colors.grey,
                                decoration: TextDecoration.lineThrough,
                                decorationColor: Colors.grey),
                          ),
                        ]),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              ],
            )));
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    search = widget.search;
    loadList();
  }

  loadList() async {
    Map map = new Map.from({
      "sign_type": createSignType(Api.URL_GOODS_LIST),
      "goods_name": search,
      'per': "10",
      'p': page.toString(),
      'sort': sort
    });
    Response<String> response =
        await HttpUtil().post(Api.URL_GOODS_LIST, data: getSign(map));
    Map userMap = json.decode(response.data);
    GoodsModelEntity itemEntity = new GoodsModelEntity.fromJson(userMap);
    print(userMap);
    if (userMap['code'] == 1) {
      if (mounted) {
        setState(() {
          if (page == 1) {
            homeListData.clear();
            _controller.finishRefresh();
            homeListData = itemEntity.data;
          } else {
            homeListData.addAll(itemEntity.data);
            _controller.finishLoad();
          }
        });
      }
    }
  }
}
